﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class NetworkManager : Photon.MonoBehaviour {
	
	private GameObject[] spawnPoints;
	private int playersConnected = 0;
	public LevelManager levelScript;
	
	void Awake()
	{
		spawnPoints = GameObject.FindGameObjectsWithTag("PlayerSpawn");
	}
	
	// Use this for initialization
	void Start () {
		PhotonNetwork.ConnectUsingSettings("CFS01");
	}
	
	void OnGUI()
	{
		GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());
	}

	void OnJoinedLobby()
	{
		Debug.Log("Joined Lobby");
		PhotonNetwork.JoinRandomRoom();
	}
	
	void OnPhotonRandomJoinFailed()
	{
		PhotonNetwork.CreateRoom("FTW");
	}
	
	void OnJoinedRoom()
	{
//		GameObject myCharacter = PhotonNetwork.Instantiate("Player_CFS", spawnPoints[0].transform.position, spawnPoints[0].transform.rotation, 0);
		PhotonNetwork.Instantiate("Player_CFS", spawnPoints[0].transform.position, spawnPoints[0].transform.rotation, 0);
		photonView.RPC("PlayerConnected",PhotonTargets.AllBuffered);
	}
	
	[RPC]
	void PlayerConnected()
	{
		int NumberOfPlayers = PlayerPrefs.GetInt("Number of players");
		
		if(NumberOfPlayers > 0 || NumberOfPlayers < 9)
		{
			NumberOfPlayers = 1;	
		}
		
		Debug.Log("Number Of Players " + NumberOfPlayers);
		
		playersConnected++;
		if(playersConnected >= NumberOfPlayers)
		{
			if(PhotonNetwork.isMasterClient)
			{
				levelScript.InstantiateTurrets();
				levelScript.InstantiatePickUps();
			}
		}
	}
}
